package cn.etynit.pet.service.impl;

import cn.etynit.pet.domain.Pet;
import cn.etynit.pet.domain.PetType;
import cn.etynit.pet.mapper.PetMapper;
import cn.etynit.pet.mapper.PetTypeMapper;
import cn.etynit.pet.service.IPetTypeService;
import cn.etynit.basic.service.impl.BaseServiceImpl;
import com.sun.org.glassfish.external.statistics.AverageRangeStatistic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etynit
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    public List<PetType> petTypeTree() {
        List<PetType> result = new ArrayList<>();
        List<PetType> allPetType = petTypeMapper.findAll();
        if (CollectionUtils.isEmpty(allPetType)){
            return result;
        }
        // stream流
        Map<Long,PetType> parentMap = allPetType.stream().collect(Collectors.toMap(PetType::getId,e->e));
        // 遍历
        for (PetType petType : allPetType){
            if (null == petType.getPid()){
                // 它就是最大的那个die
                result.add(petType);
            } else {
                // 当前的这个petType 是个儿子
                // 找爹 自己是个儿子 有爹的id
                PetType parent = parentMap.get(petType.getPid());
                if (null == parent){
                    break;
                }
                List<PetType> children = parent.getChildren();
                children.add(petType);
            }
        }
        return result;
    }

    /**
     * 删除宠物类
     * @param id
     */
    @Override
    public void delete(Long id) {
        super.delete(id);
        // 下架相应的宠物
        List<Long> ids = petMapper.findByTypeId(id);
        petMapper.batchOffsale(ids);
    }

    @Override
    public void batchDel(List<Long> ids) {
        super.batchDel(ids);
    }
}
